const app = getApp();
const { module } = app.siteInfo;
const _util = require('../util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    guests: [],
    guestsCount: 0,
    defaultAvatar: './img/default-avatar.png',
    page: 2,
    keyword: '',
    selectedTags: [],
    showTagSelector: false,
    tagGroup: [],
    transferring: false,
    checkedCount: 0,
    showSaleSelector: false,
    saleOpenID: '',
    isWXWork: app.isWXWork,
    isLoaded: false,
    tabActive: 0,
    isOpenOrder: 0,
    orderPage:1,
    order_list: [],
    loadingOrder: true,
    orderPSize:10,
    unit:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { cardId } = options;
    this.setData({ cardId });
    let masterInfo = wx.getStorageSync('masterInfo');
    this.setData({ masterInfo });
    this.checkShowCardMenu();
    app.loadCurrencyUnit().then(res => {
      this.setData({
        unit: res.unit
      });
    });
    this.getGuestsList();
  },

  getGuestsList() {
    const that = this;
    this.setData({ page: 2, guestsCount: 0 });

    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    if (!openid) {
      if (module === 'ws_micro_shop') {
        app.ws_micro_shoplogin().then(function() {
          openid = wx.getStorageSync('OPENID');
          that.setData({ openid });
          that.getGuestsInfo({ mode: 'init' });
        });
      } else {
        app.util._wxLogin().then(res => {
          openid = res.openid ? res.openid : res.data.data.openid;
          that.setData({ openid });
          that.getGuestsInfo({ mode: 'init' });
        });
      }
    } else {
      this.setData({ openid });
      this.getGuestsInfo({ mode: 'init' });
    }
  },

  // 判断是否展示订单入口
  checkShowCardMenu(){
    app.util.request({
      url:'card/api/checkShowCardMenu',
      success: res =>{
        if(res.data.errno == 0){
          this.setData({
            isOpenOrder: 1
          })
          this.getCardOrderList();
        } else {
          this.setData({
            isOpenOrder: 0
          })
        }
      }
    })
  },

  // 获取订单列表数据
  getCardOrderList(){
    let { orderPage, orderPSize, keyword, order_list } = this.data;
    app.util.request({
      url:'card/api/CardOrderList',
      data:{
        page: orderPage,
        psize: orderPSize,
        keyword: keyword
      },
      success: res =>{
        if(res.data.errno == 0){
          this.setData({
            order_list: orderPage==1 ? res.data.data: [...order_list,...res.data.data]
          })
          if (res.data.data.length < 10) {
            this.setData({
              loadingOrder: false
            })
          }
        }
      },
    })
  },

  getMoreOrder(){
    if (!this.data.loadingOrder) return;
    this.data.orderPage++;
    this.getCardOrderList();
  },

  // 获取访客列表数据
  getGuestsInfo(opts = {}) {
    let that = this;
    let { openid, cardId, type, keyword } = this.data;
    let page = opts.page && String(opts.page) || '1';
    const data = {
        openid,
        op: '1',
        page,
        pagesize: '15',
        cardid: cardId,
    };
    if (type) {
      data.type = type;
      data.keyword = keyword;
    }
    if (this.data.transferring) {
      data.relation = 'sale';
    } else {
      data.relation = '';
    }
    return new Promise((resolve, reject) => app.util.request({
      url: 'card/api/get_member_record',
      data,
      showLoading: true,
      success: res => {
        if (opts.mode === 'init') {
          if (Number(res.data.errno) === 0) {
            const guests = res.data.data.list;
            const guestsCount = res.data.data.total;
            that.setData({
              guests,
              guestsCount,
            });
          }
        } else {
          resolve(res);
        }
      },
      fail: err => {
        reject(new Error(err));
      },
      complete: ()=> {
        this.setData({
          isLoaded: true
        })
        wx.stopPullDownRefresh();
      },
    }));
  },

  // 下拉刷新最新数据。覆盖当前数据。
  onPullDownRefresh: function () {
    const that = this;
    this.setData({ page: 2, guestsCount: 0 });
    const { guests } = this.data;
    this.getGuestsInfo({ mode: 'init' }).then(res => {
      if (Number(res.data.errno) === 0) {
        const newGuests = res.data.data.list;
        const newGuestsCount = res.data.data.total;
        if (newGuests.length > 0 && newGuests[0].id !== guests[0].id) {
          that.setData({
            guests: newGuests,
            guestsCount: newGuestsCount,
          });
        } else {
          wx.showToast({
            title: '没有新记录',
            icon: 'none',
          });
        }
      }
    });
  },

  // 上拉加载历史数据，page要递增。
  getMoreGuests: function () {
    const that = this;
    let { guests, page, guestsCount } = this.data;
    this.setData({
      isLoading: true,
    });
    Number(guestsCount) > 14 && this.getGuestsInfo({ page }).then(res => {
      if (Number(res.data.errno) === 0) {
        const newGuests = res.data.data.list;
        const newGuestsCount = res.data.data.total;
        if (newGuests.length > 0) {
          that.setData({
            guests: [...guests, ...newGuests],
            guestsCount: newGuestsCount,
            page: Number(page) + 1,
          });
        } else {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        }
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none',
        });
      }
      that.setData({
        isLoading: false,
      });
    }).catch(err => {
      that.setData({
        isLoading: false,
      });
    });
  },

  gotoMsg(e) {
    const { guestOpenid } = e.currentTarget.dataset;
    const { openid, cardId } = this.data;
    this.data.isWXWork && _util.requestSubscribeMessage();
    const url = '/common/component/universal-card/pages/message?openid=' + openid + '&to_openid=' + guestOpenid + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },

  doCall(e) {
    const { phone: phoneNumber } = e.currentTarget.dataset;
    const exp = app.util.phoneExp.mobile;
    if (phoneNumber && exp.test(phoneNumber)) {
      wx.makePhoneCall({
        phoneNumber,
      });
    } else if (phoneNumber && !exp.test(phoneNumber)) {
      wx.showToast({
        title: '无效的号码',
        icon: 'none',
      });
    } else {
      wx.showToast({
        title: '该用户没留下手机号码',
        icon: 'none',
      });
    }
  },

  gotoCustomerInfo(e) {
    app.universal_card_globalData = {};
    app.universal_card_globalData.currentCustomer = e.currentTarget.dataset.customer;
    app.util.navigateTo('common/component/universal-card/pages/customer-info/customer-info?id=' + e.currentTarget.dataset.customerId);
  },

  keywordChange(e) {
    const value = e.detail.value;
    this.setData({ keyword: value });
  },

  searchCustomers() {
   if(this.data.tabActive == 0){
     this.setData({
       type: 1,
     }, () => {
       this.getGuestsInfo({})
         .then(res => {
           if (res.data && res.data.errno === 0) {
             const guests = res.data.data.list;
             const guestsCount = res.data.data.total;
             this.setData({
               guests: guests,
               guestsCount: guestsCount,
             });
           }
         });
     });
   } else {
     this.setData({
       orderPage: 1,
       order_list: [],
       loadingOrder:true,
     })
     this.getCardOrderList();
   }
  },

  getTagList() {
    let { selectedTags } = this.data;
    app.util.request({
      url: 'card/api/qyTagList',
      data: {
        openid: this.data.openid,
        client_openid: this.data.openid,
      },
      success: res => {
        if (res.data && res.data.data && res.data.errno === 0) {
          const qyTagsArr = res.data.data.qy;
          qyTagsArr.forEach(tags=>{
            tags.tags.forEach(tagItem => {
              tagItem.active = selectedTags.indexOf(tagItem.tag_name) > -1;
            })
          })
          this.setData({ tagGroup: qyTagsArr });
        }
      },
    });
  },

  selectTag() {
    this.setData({ showTagSelector: true });
    this.getTagList();
  },

  tagTapped(e) {
    const { index, groupIndex } = e.currentTarget.dataset;
    const active = this.data.tagGroup[groupIndex].tags[index].active;
    this.setData({
      [`tagGroup[${groupIndex}].tags[${index}].active`]: !active,
    });
  },

  resetTags() {
    const tagGroup = this.data.tagGroup;
    for (let i = 0; i < tagGroup.length; i++) {
      const group = tagGroup[i];
      group.tags = group.tags.map(v => ({
        ...v,
        active: false,
      }));
    }
    this.setData({ tagGroup });
  },

  searchCustomersByTag() {
    let selectedTags = [];
    for (let i = 0; i < this.data.tagGroup.length; i++) {
      const group = this.data.tagGroup[i];
      selectedTags = selectedTags.concat(group.tags.filter(v => v.active));
    }
    selectedTags = selectedTags.map(v => v.tag_name);
    this.setData({
      showTagSelector: false,
      tagGroup: [],
      type: selectedTags.length > 0 ? 2 : 1,
      selectedTags,
      keyword: selectedTags.join(','),
    }, () => {
      this.getGuestsInfo({})
        .then(res => {
          if (res.data && res.data.errno === 0) {
            const guests = res.data.data.list;
            const guestsCount = res.data.data.total;
            this.setData({
              guests: guests,
              guestsCount: guestsCount,
            });
          }
        });
    });
  },

  startTransfer() {
    this.setData({ transferring: true }, () => {
      this.getGuestsInfo({ mode: 'init' });
    });
  },

  stopTransfer() {
    this.setData({
      transferring: false,
      checkedCount: 0,
    }, () => {
      this.getGuestsInfo({ mode: 'init' });
    });
  },

  onCustomerChanged(e) {
    const checkedIndexes = e.detail.value;
    const guests = this.data.guests;
    for (let i = 0; i < guests.length; i++) {
      const guest = guests[i];
      guest.checked = checkedIndexes.indexOf(`${i}`) > -1;
    }
    this.setData({ guests, checkedCount: checkedIndexes.length });
  },

  selectedAll(e) {
    const value = e.detail.value;
    const allSelected =  value.indexOf('all') > -1;
    const guests = this.data.guests;
    for (let i = 0; i < guests.length; i++) {
      const guest = guests[i];
      guest.checked = allSelected;
    }
    this.setData({ guests, checkedCount: allSelected ? guests.length : 0 });
  },

  transferCustomer() {
    if (this.data.checkedCount === 0) {
      wx.showToast({
        title: '请选择要转移的客户',
        icon: 'none',
      });
    } else {
      this.setData({ showSaleSelector: true });
      this.getSaleList();
    }
  },

  getSaleList() {
    app.util.request({
      url: 'card/api/sale_list',
      data: {
        m_openid: this.data.openid,
      },
      success: res => {
        if (res.data && res.data.errno === 0) {
          this.setData({
            saleList: res.data.data,
          });
        }
      },
    });
  },

  onSaleChanged(e) {
    this.setData({ saleOpenID: e.detail.value });
  },

  closeSaleDialog() {
    this.setData({ showSaleSelector: false, saleOpenID: '' });
  },

  saleSelected() {
    if (this.data.saleOpenID) {
      app.util.request({
        url: 'card/api/custom_exchange',
        data: {
          openid: this.data.openid,
          to_openid: this.data.saleOpenID,
          client_openid: this.data.guests.filter(v => v.checked).map(v => v.openid).join(','),
        },
        success: res => {
          if (res.data && res.data.errno === 0) {
            wx.showToast({
              title: '客户转移成功',
            });
            this.stopTransfer();
          }
        },
      });
      this.closeSaleDialog();
    } else {
      wx.showToast({
        title: '请选择接收客户的销售',
        icon: 'none',
      });
    }
  },
  stopEvent() {},

  changeTab(e){
    let { index } = e.currentTarget.dataset;
    if (index == 0){
      this.setData({
        transferring: false
      })
      this.getGuestsList();
    } else {
      this.data.orderPage = 1;
      this.order_list = [];
      this.getCardOrderList();
    }
    this.setData({
      tabActive: index
    })
  },
});
